const Service = require('../../../core/service/ApiService');
const {Transactional} = require('../../../../plugin/egg-sequelize-transactional');

class StaffService extends Service {

    //登录获取密码
    async login(phone, pwd, remember) {
        const dao = this.service.mobile.staff.dao;
        const staff = await dao.findStaffByAccount(phone);
        if (!staff)
            throw new this.error.BusinessError('该账号不存在');
        const encryptedPwd = this.helper.sha1(pwd);
        if (encryptedPwd !== staff.pwd)
            throw new this.error.BusinessError('密码不正确');
        this.ctx.session.svc_staff_id = staff.svc_staff_id;
        let community_id_list = staff.community_id_list.split(',');
        if(!community_id_list) {
            community_id_list = [];
        }
        this.ctx.session.community_id_list = community_id_list;
        if (remember) {
            this.ctx.session.maxAge = 604800000; //7天
        }
    }

    async logout() {
        this.ctx.session = null;
    }

    //修改密码
    async updateStaffPwd(oldPwd, newPwd) {
        const dao = this.service.mobile.staff.dao;
        const oldPwdFromDb = await dao.getStaffPwd(this.ctx.session.svc_staff_id);
        if (!oldPwdFromDb) {
            throw new this.error.BusinessError('该用户不存在');
        }
        const eOldPwd = this.helper.sha1(oldPwd);
        if (eOldPwd !== oldPwdFromDb) {
            throw new this.error.BusinessError('旧密码不正确');
        }
        const eNewPwd = this.helper.sha1(newPwd);
        await dao.updateStaffPwd(this.ctx.session.svc_staff_id, eNewPwd);
    }

    //获取个人信息
    async getStaffInfo() {
        const dao = this.service.mobile.staff.dao;
        return dao.getStaffInfo(this.ctx.session.svc_staff_id);
    }

}

module.exports = StaffService;
